<template>
  <a-table
    :columns="columns"
    :data-source="tree"
    bordered
    size="middle"
    :pagination="false"
    :row-key="record => record.id"
    :scroll="{ x: 570 }"
    :default-expanded-row-keys="expandedRowKeys"
    :loading="loading"
    v-if="tree && tree.length > 0"
  >
    <template #bodyCell="{ column = {}, record }">
      <template v-if="column.key === 'dataAuth'">
        <div class="role-table-cell">
          <a-space>
            <span>{{ record.fileName }}</span>
          </a-space>
          <a-space
            ><iconfont
              name="#icon-yigouxuan"
              style="color: #52c419"
              v-if="record.dataAuth.data"
            />
          </a-space>
        </div>
      </template>
      <template v-else-if="functionalAuthKeys.includes(column.key)">
        <iconfont
          name="#icon-yigouxuan"
          style="color: #52c419"
          v-if="record.permission[column.key]"
        />
      </template>
    </template>
  </a-table>
  <div
    v-else
    style="
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100%;
    "
  >
    <a-spin :spinning="loading">
      <a-empty
        :image="notData"
        :description="loading ? '加载中...' : '暂无数据'"
      />
    </a-spin>
  </div>
</template>
<script setup>
import { ref, watch, reactive } from 'vue'
import { useVModel } from '@vueuse/core'
import iconfont from '@/components/iconfont.vue'
import { getRole } from '@/api/role.js'
import notData from '@/assets/images/not-data.png'
/**
 * 外部参数
 */
let props = defineProps({
  loading: { type: Boolean, default: () => false },
  tableData: { type: Object, default: () => {} },
})
/**
 * 事件定义
 */
let emit = defineEmits(['update:loading'])
/**
 * 双向绑定
 */
let loading = useVModel(props, 'loading', emit)

const columns = [
  {
    title: '数据权限',
    dataIndex: 'dataAuth',
    key: 'dataAuth',
    fixed: 'left',
    width: 200,
  },
  {
    title: '功能权限',
    dataIndex: 'functionalAuth',
    key: 'functionalAuth',
    children: [
      {
        title: '编辑',
        dataIndex: 'edit',
        key: 'edit',
        align: 'center',
        width: 60,
      },
      {
        title: '移动/复制',
        dataIndex: 'move',
        key: 'move',
        align: 'center',
        width: 88,
      },
      {
        title: '废除',
        dataIndex: 'delete',
        key: 'delete',
        align: 'center',
        width: 60,
      },
      {
        title: '上传',
        dataIndex: 'upload',
        key: 'upload',
        align: 'center',
        width: 60,
      },
      {
        title: '下载',
        dataIndex: 'download',
        key: 'download',
        align: 'center',
        width: 60,
      },
      {
        title: '导入',
        dataIndex: 'import',
        key: 'import',
        align: 'center',
        width: 60,
      },
      {
        title: '导出',
        dataIndex: 'export',
        key: 'export',
        align: 'center',
        width: 60,
      },
      {
        title: '预览',
        dataIndex: 'preview',
        key: 'preview',
        align: 'center',
        width: 60,
      },
    ],
  },
]
// 定义所有功能权限的键值
const functionalAuthKeys = [
  'edit',
  'move',
  'delete',
  'upload',
  'download',
  'import',
  'export',
  'preview',
]
// 查看选项
let tree = ref([])
let expandedRowKeys = ref([]) // 用于存储需要展开的行键
watch(
  () => props.tableData,
  tableData => {
    console.log()
    tree.value = []
    expandedRowKeys.value = []
    tree.value = tableData
    tree.value.forEach(node => cleanEmptyChildren(node))
    let nodes = collectExpandedNodes(tree.value)
    expandedRowKeys.value = filterExpandedNodes(nodes, tree.value)
  },
  { deep: true, immediate: true },
)
// 递归地清理单个树结构中的空children
function cleanEmptyChildren(node) {
  if (Array.isArray(node.children) && node.children.length === 0) {
    delete node.children
  } else if (node.children && node.children.length > 0) {
    for (let i = 0; i < node.children.length; i++) {
      cleanEmptyChildren(node.children[i])
    }

    // 再次检查是否为空数组，因为子节点可能已经被删除
    if (node.children.length === 0) {
      delete node.children
    }
  }
}
/**
 * 收集需要展开的节点
 */
function collectExpandedNodes(tree) {
  const expandedNodeIds = new Set()
  function traverse(node, path = []) {
    // 检查当前节点是否满足条件
    const hasTrueValues =
      node.dataAuth.data || Object.values(node.permission).some(v => v)

    if (hasTrueValues) {
      // 如果满足条件，添加路径上的所有节点
      for (const nodeId of path) {
        expandedNodeIds.add(nodeId)
      }
    }
    if (node.children && node.children.length > 0) {
      // 递归处理子节点，同时更新路径
      traverseChildren(node.children, [...path, node.id])
    }
  }
  function traverseChildren(children, path) {
    for (const child of children) {
      traverse(child, path)
    }
  }

  // 遍历顶层节点
  tree.forEach(node => traverse(node))
  return Array.from(expandedNodeIds)
}
/**
 * 过滤掉拥有所有数据权限和功能权限的节点
 */
function filterExpandedNodes(expandedNodeIds, tree) {
  const result = new Set(expandedNodeIds)
  function shouldExpandChildren(node) {
    if (!node.children || node.children.length === 0) return false
    // 检查所有子节点的 dataAuth.data 和 permission 是否都为 true
    return node.children.every(
      child =>
        child.dataAuth.data && Object.values(child.permission).every(v => v),
    )
  }
  function traverse(node) {
    if (node.children && node.children.length > 0) {
      if (shouldExpandChildren(node)) {
        // 如果当前节点的 dataAuth.data 和 permission 均为 true，则不展开这些子节点
        result.delete(node.id)
      }
      for (const child of node.children) {
        if (shouldExpandChildren(child)) {
          // 如果所有子节点的 dataAuth.data 和 permission 均为 true，则不展开这些子节点
          result.delete(child.id)
        }
        traverse(child)
      }
    }
  }
  // 遍历顶层节点进行过滤
  tree.forEach(node => traverse(node))
  return Array.from(result)
}
</script>
<style lang="less" scoped>
.role-table-cell {
  display: flex;
  justify-content: space-between;
}
</style>
